package com.android.clinic.doctors.app.ui.patient;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;

import com.android.clinic.doctors.app.ClinicDoctorsApplication;
import com.android.clinic.doctors.app.R;
import com.android.clinic.doctors.app.VideoCallActivity;
import com.android.clinic.doctors.app.base.BaseActivity;
import com.android.clinic.doctors.app.ui.widget.MagicIndicatorTools;
import com.android.clinic.doctors.app.utils.Constants;
import com.jiongbull.jlog.JLog;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.agora.AgoraAPI;
import io.agora.rtc.RtcEngine;

/**
 * 患者列表
 * Created by cheng on 2018/6/19.
 */
public class PatientListActivity extends BaseActivity {

    private ViewPager mViewPager;
    private List<Fragment> mFragmentList = new ArrayList<>();

    private ReservedFragment reservedFragment;

    private final int REQUEST_CODE = 0x01;
    private String callUserName = "";   // 被呼叫的用户账号
    private String callUserImg = "";  // 被呼叫的用户头像
    private String resolvedId = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_patient_list;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("患者");

        mViewPager = findViewById(R.id.viewPager);
        initMagicIndicator();
        initFragment();
    }

    private void initFragment() {
        mFragmentList.clear();
        reservedFragment = new ReservedFragment();
        mFragmentList.add(PatientFragment.newInstance(0));  // 我的患者
        mFragmentList.add(reservedFragment);          // 已预约
        mFragmentList.add(PatientFragment.newInstance(1));  // 已处理

        mViewPager.setOffscreenPageLimit(mFragmentList.size());
        mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));

        reservedFragment.setOnVideoCallBackListener(new ReservedFragment.OnVideoCallBackListener() {

            @Override
            public void callBack(String id, String callId, String name, String imgUrl) {
                resolvedId = id;
                callUserName = name;
                callUserImg = imgUrl;
                JLog.e("userId: " + callId + ",name: " + name);
                ClinicDoctorsApplication.getInstance().getAngoraAPI().queryUserStatus(callId);
            }
        });
    }


    /**
     * 初始化分类菜单
     */
    private void initMagicIndicator() {
        String[] oldOrderArray = getResources().getStringArray(R.array.patient_array);
        MagicIndicator magicIndicator = findViewById(R.id.magic_indicator);
        MagicIndicatorTools magicTools = new MagicIndicatorTools(this);
        magicTools.setArrays(oldOrderArray);
        magicTools.setIndicator(true);
        magicTools .setAdjustMode(true);
        magicTools.builder(magicIndicator);
        magicTools .setOnClipPagerClickListener((v, position) -> mViewPager.setCurrentItem(position));
        ViewPagerHelper.bind(magicIndicator, mViewPager);
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter {

        private ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }


        @Override
        public int getCount() {
            return mFragmentList.size();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallBack();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RtcEngine.destroy();
    }

    /**
     * 声网SDK回调处理
     */
    private void addCallBack() {
        JLog.e("addCallback enter." );
        ClinicDoctorsApplication.getInstance().getAngoraAPI().callbackSet(new AgoraAPI.CallBack(){

            /**
             * 登录成功回调
             * @param uid
             * @param fd
             */
            @Override
            public void onLoginSuccess(int uid, int fd) {
                JLog.e("登录成功回调...");
            }

            /**
             * 退出登录回调
             * @param encode
             */
            @Override
            public void onLogout(int encode) {
                JLog.e("退出登录回调...");
            }

            /**
             * 登录失败回调
             * @param encode
             */
            @Override
            public void onLoginFailed(int encode) {
                JLog.e("登录失败回调...");

            }

            /**
             * 远端已收到呼叫回调
             * @param channelID  频道名
             * @param account 客户端定义的用户账号
             * @param uid 固定ID, 填0
             */
            @Override
            public void onInviteReceivedByPeer(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(PatientListActivity.this, VideoCallActivity.class);
                        intent.putExtra("account", account);
                        intent.putExtra("channelName", channelID);
                        intent.putExtra("userName", callUserName);
                        intent.putExtra("imgUrl", callUserImg);
                        intent.putExtra("type", Constants.CALL_OUT);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });
            }

            /**
             * 用户查询状态回调
             * @param name 用户账号名称
             * @param status 1:用户在线;0:用户不在线
             */
            @Override
            public void onQueryUserStatusResult(String name, String status) {
                JLog.e("当前账号name = " + name + ",status = " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 发起呼叫
                        JLog.e("发起呼叫:  " + name);
                        if (status.equals("1")) {
                            ClinicDoctorsApplication.getInstance().getAngoraAPI().channelInviteUser2(Constants.CHANNEL_ID, name, setupJSONExtra());
                        } else if (status.equals("0")) {
                            showToast("您呼叫的用户不在线, 请稍后再试...");
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        JLog.e("onActivityResult requestCode: " + requestCode + " resultCode: " + resultCode);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getStringExtra("result").equals("finish")) {
                finish();
            } else {
                String callTime = data.getStringExtra("callTime");
                JLog.e("callTime:  " + callTime);
                if (!TextUtils.isEmpty(callTime) && Integer.valueOf(callTime) >= 10) {
                    reservedFragment.postResolved(resolvedId);
                }
            }
        }
    }

    private String setupJSONExtra() {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            jsonObject.put("name", ClinicDoctorsApplication.getUserInfo().getName());
            jsonObject.put("imgUrl", ClinicDoctorsApplication.getUserInfo().getImgUrl());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

}
